package mall

import (
	"context"
	"fmt"
	"private-domain-overseas-service/admin/business/api/internal/repository/mall"
	"private-domain-overseas-service/pkg/xerr"
	"private-domain-overseas-service/tools/ent"
	"private-domain-overseas-service/tools/ent/hzmall"
	"private-domain-overseas-service/tools/ent/predicate"
	"time"

	"private-domain-overseas-service/admin/business/api/internal/svc"
	"private-domain-overseas-service/admin/business/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type MallEditLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// 添加/编辑商城
func NewMallEditLogic(ctx context.Context, svcCtx *svc.ServiceContext) *MallEditLogic {
	return &MallEditLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *MallEditLogic) MallEdit(req *types.MallEditRequest) error {
	mallDao := mall.NewMallDao(l.ctx, l.svcCtx)

	//新增
	if req.Type == "add" {
		hzMall := &ent.HzMall{
			MallSort:   req.Sort,
			MallIcon:   req.MallIcon,
			MallName:   req.MallName,
			MallURL:    req.MallUrl,
			MallStatus: req.Status,
			CreatedAt:  time.Now().Unix(),
			UpdateAt:   time.Now().Unix(),
		}
		_, err := mallDao.MallCreate(hzMall, nil)
		if err != nil {
			return xerr.ErrCodeMsg(xerr.ServerOperationExceptionError, fmt.Sprintf("添加商城图标失败：%v", err))
		}
	}

	//修改
	if req.Type == "edit" {
		//查询原始值
		conditions := make([]predicate.HzMall, 0)
		conditions = append(conditions, hzmall.IDEQ(int(req.Id)))
		hzMall, _ := mallDao.MallConditionsFirst(conditions)
		//赋值
		hzMall.MallSort = req.Sort
		hzMall.MallIcon = req.MallIcon
		hzMall.MallName = req.MallName
		hzMall.MallURL = req.MallUrl
		hzMall.MallStatus = req.Status
		hzMall.UpdateAt = time.Now().Unix()
		err := mallDao.MallUpdate(hzMall, nil)
		if err != nil {
			return xerr.ErrCodeMsg(xerr.ServerOperationExceptionError, fmt.Sprintf("编辑商城图标失败%v", err))
		}
	}

	return nil
}
